package com.bzr.emos.wx.controller;

import com.alibaba.fastjson2.JSONObject;
import com.bzr.emos.wx.Service.UserService;
import com.bzr.emos.wx.common.util.R;
import com.bzr.emos.wx.db.pojo.WechatUsers;
import com.bzr.emos.wx.tenoss.PutObject;
import com.bzr.emos.wx.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/register")
@Slf4j
public class RegisterController {

    @Autowired
    UserService userService;


    @Autowired
    PutObject putObject;


    @Autowired
    Util util;


    // 配置上传目录（根据实际需求修改）
    private static final String UPLOAD_DIR = "D://uploads/avatars/";

    @PostMapping("/avatar")
    public R uploadAvatar(
            @RequestParam("avatar") MultipartFile file,
            @RequestParam("nickname") String nickname,
            @RequestParam("code") String code,
            @RequestParam("role") String role,
            @RequestParam("register") String register
    ) throws IOException {
        log.info("昵称:{}", nickname);

        JSONObject openJson = userService.getOpenId(code);

        //判断数据库是否存在此微信用户openid
        WechatUsers weUser = userService.checkWechatUser(openJson.getString("openid"));

        if (weUser!=null) {
            return R.error().put("msg","重复注册");
        }


        String avatar_url = putObject.putTxOss(openJson.getString("openid") + "@" + nickname + ".jpeg", util.convertWithCommonsIO(file));
        WechatUsers wechatUsers = new WechatUsers();
        wechatUsers.setOpenid(openJson.getString("openid"));
        wechatUsers.setNickname(nickname);
        wechatUsers.setAvatarUrl(avatar_url);
        if (userService.addWechatUser(wechatUsers)) {
            return R.ok();
        }else{
            return R.error().put("msg","创建用户失败");
        }

    }







}